//
//  BoardDetail.m
//  LilyBBS
//
//  Created by 李行 on 11-11-28.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "BoardDetail.h"
#import "Top10Detail.h"
#import "NewTopic.h"
#import "SingleCookie.h"
#import "LogIn.h"
#import "Detail.h"
#import "Reachability.h"

@implementation BoardDetail

@synthesize detail,titlestring,previousPage,indicatorView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView
 {
 }
 */


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    viewdidload = YES;
    indicatorView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:indicatorView];
    indicatorView.center=CGPointMake(160,160);
    [indicatorView startAnimating];
    
    self.tableView.rowHeight = 70;
    [super viewDidLoad];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
    //NSLog(@"view did load");
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] 
                                              initWithTitle:@"发帖"                                            
                                              style:UIBarButtonItemStyleBordered 
                                              target:self 
                                              action:@selector(newTopic)];
    
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
        view.delegate = self;
        [self.tableView addSubview:view];
        _refreshHeaderView = view;
        [view release];
        
    }
    //  update the last update date
    [_refreshHeaderView refreshLastUpdatedDate];
}

-(void)viewWillAppear:(BOOL)animated{
}

-(void)viewDidAppear:(BOOL)animated{
    viewdidappear = YES;
    NSString* href = [NSString stringWithFormat:@"http://bbs.nju.edu.cn/bbstdoc?board=%@",self.titlestring];
    NSURL* url = [[NSURL alloc] initWithString:href];
    NSData* data = [[NSData alloc] initWithContentsOfURL:url];
    if (viewdidload) {
        [self getDetail:data];
        [self.tableView reloadData];
    }
    viewdidload = false;
    [indicatorView stopAnimating];
    [data release];
}


- (void)viewDidUnload
{
    _refreshHeaderView=nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (viewdidappear) {
        return [[detail objectAtIndex:0] count]+1;
    }
    else{
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    // Navigation logic may go here. Create and push another view controller.
    if (indexPath.row<[[detail objectAtIndex:0]count]) {
        Detail* webView = [[Detail alloc] initWithNibName:@"Detail" bundle:nil];
        NSString* href = [[@"http://bbs.nju.edu.cn/" stringByAppendingString:[[self.detail objectAtIndex:3]objectAtIndex:indexPath.row]] stringByAppendingFormat:@"&start=-1"];
        webView.titlestring = [[self.detail objectAtIndex:0] objectAtIndex:indexPath.row];
        webView.urlString = [NSString stringWithString:href];
        [self.navigationController pushViewController:webView animated:YES];
    }else{
        [indicatorView startAnimating];
        [self reloadPreviousPage];
    }
    
    /*if (indexPath.row<[[detail objectAtIndex:0]count]) {
        Top10Detail *detailViewController = [[Top10Detail alloc] initWithNibName:@"Top10" bundle:nil];
        NSString* i = @"http://bbs.nju.edu.cn/";
        NSString* href = [[i stringByAppendingString:[[self.detail objectAtIndex:3]objectAtIndex:indexPath.row]] stringByAppendingFormat:@"&start=-1"];
        NSURL* url = [[NSURL alloc] initWithString:href];
        NSData* data = [[NSData alloc] initWithContentsOfURL:url];
        [detailViewController getDetail:data];
        detailViewController.titlestring = [[self.detail objectAtIndex:0] objectAtIndex:indexPath.row];
    // ...
    // Pass the selected object to the new view controller.
        [self.navigationController pushViewController:detailViewController animated:YES];
        [detailViewController release];
    }else{
        [self reloadPreviousPage];
    }*/
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    NSMutableArray* titles = [detail objectAtIndex:0];
    NSMutableArray* authors  = [detail objectAtIndex:1];
    
    UITableViewCell* cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]autorelease];
    [cell.textLabel setNumberOfLines:2];
    //UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    //在最后一个cell里加载“下一页”
    //NSLog(@"%i",[[detail objectAtIndex:0]count]);
    if (indexPath.row<[[detail objectAtIndex:0]count]) {
        cell.textLabel.text = [titles objectAtIndex:indexPath.row];
        //NSLog(@"title:%@",[titles objectAtIndex:indexPath.row]);
        NSString* author = @"作者：";
        cell.detailTextLabel.text = [author stringByAppendingString:[authors objectAtIndex:indexPath.row]];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else{
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.textLabel.text = @"下一页";
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    return cell;
}

-(void)getDetail:(NSData *)data{
    //返回的detail类型为：(titles,authors,follownumber,href)
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);    
    
    NSString* href1 = [NSString stringWithFormat:@"http://bbs.nju.edu.cn/bbstdoc?board=%@",self.titlestring];
    NSURL* url = [[NSURL alloc] initWithString:href1];
    NSLog(@"%i",[href1 retainCount]);
    ASIHTTPRequest* request = [[ASIHTTPRequest alloc]initWithURL:url];
    [url release];
    [request setDelegate:self];
    [request startSynchronous];
    NSData* requestData = [request responseData];
    [request release];
    [href1 release];
    TFHpple* xpathParser = [[TFHpple alloc] initWithHTMLData:requestData];
    
    //由于times抓取有问题，且置顶帖抓取有也问题，因此两者都不做
	//TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:data];
	NSArray *titles = [xpathParser searchWithXPathQuery:@"//tr/td[5]/a"];//19
    //NSMutableArray *times = [xpathParser searchWithXPathQuery:@"//tr[position()>1]/td[4]"];//19，而且有问题
    NSArray *authors = [xpathParser searchWithXPathQuery:@"//tr[td[6]/font[2]]/td[3]/a"];//22
    NSArray *follownumber = [xpathParser searchWithXPathQuery:@"//td[6]/font[position()=1]"];//19
    NSArray* href = [xpathParser searchWithXPathQuery:@"//td[5]/a/@href"];//19
    NSArray* previouspage = [xpathParser searchWithXPathQuery:@"//hr[2]/following::a[1]/@href"];//存放上一页的地址
	
    NSMutableArray* arr = [[NSMutableArray alloc] init];
    //detail[0]
    NSMutableArray* titlearr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in titles) {
		NSString *strs = [element content];
        if (strs==NULL) {
            continue;
        }
        NSString* realStr = [strs substringFromIndex:2];
		[titlearr insertObject:realStr atIndex:0];
    }
    [arr addObject:titlearr];
    //detail[1]
    NSMutableArray* authorarr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in authors) {
		NSString *strs = [element content];
		[authorarr insertObject:strs atIndex:0];
    }
    [arr addObject:authorarr];
    //detail[2]
    NSMutableArray* follownumberarr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in follownumber) {
		NSString *strs = [element content];
		[follownumberarr insertObject:strs atIndex:0];
    }
    [arr addObject:follownumberarr];
    //detail[3]
    NSMutableArray* hrefarr = [[NSMutableArray alloc] init];
	for (TFHppleElement *element in href) {
		NSString *strs = [element content];
        //NSLog(@"%@",strs);
		[hrefarr insertObject:strs atIndex:0];
    }
    [arr addObject:hrefarr];
    
    //找到上一页的地址，为加载上一页作准备
    for(TFHppleElement* element in previouspage){
        NSString* strs = [element content];
        self.previousPage = strs;
    }
    
	self.detail = arr;
	//[arr release];
    //[titles release];
    //[authors release];
    //[follownumber release];
    //[href release];
    [titlearr release];//19
    [authorarr release];//19
    [follownumberarr release];//19
    [hrefarr release];//19
	[xpathParser release];
}

-(void)reloadPreviousPage{
    [[self.detail objectAtIndex:0] removeLastObject];
    [[self.detail objectAtIndex:1] removeLastObject];
    [[self.detail objectAtIndex:2] removeLastObject];
    [[self.detail objectAtIndex:3] removeLastObject];
    NSInteger numberOfDetail = [[self.detail objectAtIndex:0] count];
    NSString* i = @"http://bbs.nju.edu.cn/";
    NSString* previoushref = [i stringByAppendingString:self.previousPage];
    NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:previoushref]];
    
    //返回的detail类型为：(titles,authors,follownumber,href)
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGBK_95);    
    
    //由于times抓取有问题，且置顶帖抓取有也问题，因此两者都不做
	NSString* href1 = [NSString stringWithFormat:@"http://bbs.nju.edu.cn/%@",self.previousPage];
    //NSLog(@"%@",href);
    NSURL* url = [[NSURL alloc] initWithString:href1];
    ASIHTTPRequest* request = [[ASIHTTPRequest alloc]initWithURL:url];
    [href1 release];
    [request setDelegate:self];
    
    [request setResponseEncoding:enc];
    [request startSynchronous];
    ASIHTTPRequest* requestData = [request responseData];
    [request release];
    TFHpple* xpathParser = [[TFHpple alloc] initWithHTMLData:requestData];
    [requestData release];
	NSMutableArray *titles       = [xpathParser searchWithXPathQuery:@"//tr/td[5]/a"];//19
    NSMutableArray *authors      = [xpathParser searchWithXPathQuery:@"//tr[td[6]/font[2]]/td[3]/a"];//19
    NSMutableArray *follownumber = [xpathParser searchWithXPathQuery:@"//td[6]/font[position()=1]"];//19
    NSMutableArray* href         = [xpathParser searchWithXPathQuery:@"//td[5]/a/@href"];//19
    NSMutableArray* previouspage = [xpathParser searchWithXPathQuery:@"//hr[2]/following::a[1]/@href"];//存放上一页的地址
	
    //detail[0]
	for (TFHppleElement *element in titles) {
		NSString *strs = [element content];
        if (strs==NULL) {
            continue;
        }
        NSString* realStr = [strs substringFromIndex:2];
		[[self.detail objectAtIndex:0] insertObject:realStr atIndex:numberOfDetail];
        //[strs release];
    }
    //detail[1]
	for (TFHppleElement *element in authors) {
		NSString *strs = [element content];
		[[self.detail objectAtIndex:1] insertObject:strs atIndex:numberOfDetail];
    }
    //detail[2]
	for (TFHppleElement *element in follownumber) {
		NSString *strs = [element content];
		[[self.detail objectAtIndex:2] insertObject:strs atIndex:numberOfDetail];
    }
    //detail[3]
	for (TFHppleElement *element in href) {
		NSString *strs = [element content];
        //NSLog(@"%@",strs);
		[[self.detail objectAtIndex:3] insertObject:strs atIndex:numberOfDetail];
    }
    
    //找到上一页的地址，为加载上一页作准备
    for(TFHppleElement* element in previouspage){
        NSString* strs = [element content];
        self.previousPage = strs;
    }
    
    //刷新tableview
    [self.tableView reloadData];
}

-(void)newTopic{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.nju.edu.cn"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable:
            //没有网络连接
            NSLog(@" ");
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络好像连接不上。。。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil];
            [alert show];
            [alert release];
            return;
        case ReachableViaWWAN:
            //使用3G网络            
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络            
            break;
    }
    
    //若未登录，则提示
    if ([[SingleCookie sharedSingleCookie].savedCookies count]==0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"回复提示" message:@"尚未登录，请登录后回复。" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录", nil];
        [alert show];
        [alert release];
        return;
        //[self dismissModalViewControllerAnimated:YES];
    }
    
    NewTopic* topic = [[NewTopic alloc] initWithNibName:@"NewTopic" bundle:nil];
    topic.boardName = self.titlestring;
    UINavigationController *topicCon = [[UINavigationController alloc] initWithRootViewController:topic];
    [self presentModalViewController:topicCon animated:YES];
}

//响应alert中“登录”按钮
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            break;
        case 1:
            NSLog(@" ");
            LogIn* login = [[LogIn alloc] initWithNibName:@"LogIn" bundle:nil];
            UINavigationController *addNavCon = [[UINavigationController alloc] initWithRootViewController:login];
            [self presentModalViewController:addNavCon animated:YES];
            [login release];
            break;
            
        default:
            break;
    }
}

-(void)dealloc{
    [detail release];
    [titlestring release];
    _refreshHeaderView = nil;
    [previousPage release];
    [super dealloc];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    //  should be calling your tableviews data source model to reload
    //  put here just for demo
    _reloading = YES;
    NSString* href = [NSString stringWithFormat:@"http://bbs.nju.edu.cn/bbstdoc?board=%@",self.titlestring];
    NSURL* url = [[NSURL alloc] initWithString:href];
    NSData* data = [[NSData alloc] initWithContentsOfURL:url];
    [self getDetail:data];
}

- (void)doneLoadingTableViewData{
    //  model should call this when its done loading
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    [self reloadTableViewDataSource];

    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1.0];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    return [NSDate date]; // should return date data source was last changed
}

@end
